﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Security.Cryptography;
using System.IO;
using EncyptDemo;
namespace SoftRegTest
{
    public partial class Form1 : Form
    {
        private static RSACryption rsa = new RSACryption();
        private static RSAHelper rsah = new RSAHelper(); //用于签名和验证
        private KeyManages _Keys;
        public Form1()
        {
            InitializeComponent();
            _Keys = new KeyManages();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            if (!InitLocalMode())
            {
                MessageBox.Show("配置错误，即将退出");
                this.Close();
            }
        }
        private Boolean InitLocalMode()
        {
            List<KeyInfo> list = _Keys.Keys;
            if (list.Count == 0)
                return false;
            comboBoxPublicKey.Items.Clear();
            comboBoxPublicKey.Items.AddRange(list.ToArray());
            return true;
        }
        private void buttonRefreshPublickey_Click(object sender, EventArgs e)
        {
            if (InitLocalMode())
                MessageBox.Show("已刷新");
            else
                MessageBox.Show("路径不正确，未刷新");
        }
        private void buttonMakeKeys_Click(object sender, EventArgs e)
        {
            _Keys.ProduceXmlKeys();
            buttonRefreshPublickey.PerformClick();
        }
        private void comboBoxPublicKey_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBoxPublicKey.SelectedIndex == -1)
                return;
            KeyInfo _ActiveKeyInfo = (KeyInfo)comboBoxPublicKey.SelectedItem;

            textBoxPrivateKey.Text = _ActiveKeyInfo.PrivateKey();
            textBoxPublicKey.Text = _ActiveKeyInfo.PublicKey();
            //Tools.SoftRegisterTools.SetPublicKey(_ActiveKeyInfo.PublicKey);
        }
        private void buttonPublicKeyCode_Click(object sender, EventArgs e)
        {
            try
            {
                textBoxMiWen.Text = rsa.RSAEncrypt(textBoxPublicKey.Text, textBoxMingWen.Text);
            }
            catch { }
        }
        private void buttonPrivateKeyDeCode_Click(object sender, EventArgs e)
        {
            try
            {
                textBoxMingWen.Text = rsa.RSADecrypt(textBoxPrivateKey.Text, textBoxMiWen.Text);
            }
            catch { }
        }

        private void buttonSignatureFormatter_Click(object sender, EventArgs e)
        {
            try
            {
                rsah.privateKey = textBoxPrivateKey.Text;
                rsah.publicKey = textBoxPublicKey.Text;
                textBoxMiWen.Text = rsah.Sign(textBoxMingWen.Text);

                byte[] bt = Encoding.GetEncoding("utf-8").GetBytes(textBoxMiWen.Text);
                var sha256 = new SHA256CryptoServiceProvider();
                byte[] rgbHash = sha256.ComputeHash(bt);
                StringBuilder sb = new StringBuilder(32);
                for (int i = 0; i < rgbHash.Length; i++)
                {
                    sb.Append(rgbHash[i].ToString("x").PadLeft(2, '0'));
                }

                textBoxSignHash.Text = sb.ToString();
                    //;Encoding.GetEncoding("utf-8").GetString(rgbHash);
            }
            catch { }
        }
        private void buttonSignatureDeformatter_Click(object sender, EventArgs e)
        {
            try
            {
                string mingwen = textBoxMingWen.Text;
                string miwen= textBoxMiWen.Text;
                if (  rsah.SignCheck(mingwen,miwen))
                    MessageBox.Show("签名签证成功");

            }
            catch { }
        }
        private void buttonGetResistInformatica_Click(object sender, EventArgs e)
        {
            textBoxOrginText.Text = Tools.SoftRegisterTools.getMachineNum();
        }
        private void buttonRegistShow_Click(object sender, EventArgs e)
        {

        }
        private void buttonCopyToMingWen_Click(object sender, EventArgs e)
        {
            textBoxMingWen.Text = textBoxOrginText.Text;
        }

        private void buttonAddTime_Click(object sender, EventArgs e)
        {
          textBoxMingWen.Text =  AddTime(textBoxOrginText.Text,24);
        }

        private void buttonConstructionRegistInfo_Click(object sender, EventArgs e)
        {
          textBoxMiWen.Text = ConstructionRegistInfo(textBoxMingWen.Text, textBoxMiWen.Text);
        }
        private void buttonReCode_Click(object sender, EventArgs e)
        {
            textBoxSignHash.Text = "<" + textBoxOrginText.Text + ":" +
                (new WebEncryptor()).SHA1(textBoxMiWen.Text) +":" +
                DESHeper.EncryptDES(textBoxMiWen.Text, "love2018") + ">";


            return;
            textBoxSignHash.Text ="md5: "+ (new MD5Helper()).GetMD5_32(textBoxMiWen.Text)+"\r\nmd5: "
            + (new WebEncryptor()).MD5(textBoxMiWen.Text) + "\r\nsha1: "
                + (new WebEncryptor()).SHA1(textBoxMiWen.Text) + "\r\nDes: "
                + DESHeper.EncryptDES(textBoxMiWen.Text, "love9815") + "\r\n  mingwen\r\n" +
                DESHeper.DecryptDES(DESHeper.EncryptDES(textBoxMiWen.Text, "love9815"), "love9815") + "\r\n";
        }

        private string AddTime(string orgin, int months)
        {
            int year = months / 12;
            int month = months % 12;
            DateTime dt = new DateTime(2018, 1, 1);
            DateTime dt1 = DateTime.Now;
            DateTime dt2 = dt1.AddYears(year);
            dt2 = dt2.AddMonths( month);

            return orgin + "#" + (int)( (dt1 - dt).TotalDays) + "-" + (dt2 - dt1).TotalDays;
        }
        private string ConstructionRegistInfo(string machinecode, string sign)
        {
            return "<SIGN>[sign]</SIGN><MACHINECODE>[machinecode]</MACHINECODE>"
                .Replace("[machinecode]",machinecode).Replace("[sign]",sign);
        }
    }
    public class ScanDatas
    {
        private List<ScanData> _scandatas;
        private string path;
        public ScanDatas(string path)
        {
            this.path = path;
            _scandatas = new List<ScanData>();
            foreach (string dirname in Tools.FileTools.SubDirNameListFromDir(path))
            {
                ScanData sd = new ScanData(dirname, path);
                if (sd.ImgList.Count > 0)
                    Scandatas.Add(sd);
            }
        }
        public List<ScanData> Scandatas { get { return _scandatas; } }
    }
    public class ScanData
    {
        private string _dirname;
        private string _path;
        private string _examname;
        public ScanData(string dirname, string path)
        {
            this._dirname = dirname;
            this._path = path;
            _examname = dirname;
            if (dirname.Contains("."))
            {
                _examname = dirname.Substring(0, dirname.LastIndexOf("."));
            }
        }
        public override string ToString()
        {
            if (File.Exists(Fullpath + "\\已生成阅卷数据.txt"))
                return _examname + " 已生成阅卷数据";
            return _examname;
        }
        public string Fullpath { get { return _path + "\\" + _dirname; } }
        public string Imgpath { get { return _path + "\\" + _dirname; } }
        public string DataFullName { get { return Fullpath + "\\data.txt"; } }
        public string ExamName { get { return _examname; } }
        public List<KeyInfo> KeyList
        {
            get
            {
                List<KeyInfo> list = new List<KeyInfo>();
                foreach (string s in GetFileList(".pub"))
                {
                    string path = s.Substring(0, s.LastIndexOf("\\") + 1);
                    string name = s.Substring(path.Length);
                    name = name.Substring(0, name.Length - 4);   
                    list.Add(new KeyInfo(path , name));
                }
                return list;
            }
        }

        public List<string> ImgList { get { return Tools.FileTools.NameListFromDir(Imgpath, ".jpg"); } }
        public List<string> GetFileList(string ext)
        {
            return Tools.FileTools.NameListFromDir(Fullpath, ext);
        }

        public string GetNewXmlFileName()
        {
           int maxcount = 0;
           foreach (KeyInfo ki in KeyList)
           {
               if (ki.ToString().Contains("xmlkeys"))
               {
                   string s = ki.ToString().Substring(7);
                   if (Tools.ValidTools.ValidNumber(s))
                   {
                       int index = Convert.ToInt32(s);
                       maxcount = maxcount > index ? maxcount : index;
                   }
               }
           }
           maxcount++;
           return Fullpath + "\\xmlkeys" + maxcount;
        }

        public  void Refresh()
        {
            //throw new NotImplementedException();
        }
    }
    public class KeyInfo
    {
        public KeyInfo(string path,string name)
        {
            Path = path;
            Name = name;
        }
        public string PublicKey()
        {
            return File.ReadAllText(Path + Name + ".pub");
        }
        public string PrivateKey()
        {
            return File.ReadAllText(Path + Name );
        }
        public override string ToString()
        {
            return Name;
        }
        private string Path; //带后缀
        private string Name;
    }

    public class KeyManages
    {
        public KeyManages()
        {
            _Sd = null;
            _keys = null;
            LoadKeys();
        }
        public void ProduceXmlKeys()
        {
            if (_Sd != null)
            {
                string xmlkey = "";
                string xmlpublickey = "";
                rsa.RSAKey(out xmlkey, out  xmlpublickey);

                string filename = _Sd.GetNewXmlFileName();
                File.WriteAllText(filename, xmlkey);
                File.WriteAllText(filename + ".pub", xmlpublickey);
                _Sd.Refresh();
                _keys = null;
            }
        }

        private void LoadKeys()
        {
            if (File.Exists("Config.ini"))
            {
                string path = File.ReadAllText("Config.ini").Trim();
                if (Directory.Exists(path))
                {
                    DirectoryInfo di = new DirectoryInfo(path);                   
                    _Sd = new ScanData("keys", ".");
                    if (Directory.Exists(_Sd.Imgpath))
                    {
                        _keys = _Sd.KeyList;
                    }
                }
            }
        }
        public List<KeyInfo> Keys
        {
            get
            {
                if (_keys == null)
                    LoadKeys();
                return _keys;
            }
        }
        private List<KeyInfo> _keys;
        private ScanData _Sd;
        private static RSACryption rsa = new RSACryption();
    }

}